/// Settings ///

using System;
using System.Xml;
using System.IO;

namespace Xyne
{
	class Settings
	{
		private const string SETTINGS_FILENAME = "settings";
		private const string ROOT_NAME = "Xyne";
		private const string PLAYER_NAME_KEY = "Player-Name";
		private const string PLAYER_NAME_DEFAULT = "Player";
		
		private static Settings instance = new Settings();
		private XmlDocument document;
		private XmlNode root;
		private XmlNode playerName;
		
		public String PlayerName
		{
			get { return playerName.InnerText; }
			set { playerName.InnerText = value; }
		}
		
		public static Settings GetSettings() { return instance; }
		
		private Settings()
		{
		}
		
		public void Save()
		{
			try
			{
				document.Save(SETTINGS_FILENAME);
			}
			catch( Exception ) {} 
		}
		
		public bool Load()
		{
			document = new XmlDocument();
			
			try
			{
				document.Load(SETTINGS_FILENAME);
				root = document.ChildNodes.Item(1);
			}
			catch( FileNotFoundException )
			{    
				try
				{
					// declaration
					XmlNode declaration = document.CreateNode(XmlNodeType.XmlDeclaration,"","");
					document.AppendChild(declaration);
					// root
					root = document.CreateElement("",ROOT_NAME,"");
					document.AppendChild(root);
					document.Save(SETTINGS_FILENAME);
				}
				catch( Exception )
				{
				}
			}
			catch( Exception )
			{
				return false;
			}

			if( root != null && root.LocalName == ROOT_NAME )
			{
				bool foundPlayerName = false;
				for( int i = 0; i < root.ChildNodes.Count; i++ )
				{
					if( root.ChildNodes.Item(i).LocalName == PLAYER_NAME_KEY )
					{
						playerName = root.ChildNodes.Item(i);
						foundPlayerName = true;
					}
				}
				
				if( !foundPlayerName )
				{
					playerName = document.CreateElement("",PLAYER_NAME_KEY,"");
					playerName.InnerText = PLAYER_NAME_DEFAULT;
					root.AppendChild(playerName);
				}
				
				if( !foundPlayerName )
					Save();
				
				return true;
			}
			
			return false;
		}
	}
}